package com.ricchieri.service;

import java.io.Serializable;
import java.util.List;

import org.springframework.transaction.annotation.Transactional;

import com.ricchieri.dao.interf.IEmailTemplateDao;
import com.ricchieri.filter.EmailTemplateFilter;
import com.ricchieri.model.EmailTemplate;
import com.ricchieri.service.interf.IEmailTemplateService;

@Transactional(readOnly = true)
public class EmailTemplateService implements IEmailTemplateService, Serializable {
	private static final long serialVersionUID = 6216248906164996960L;
	IEmailTemplateDao emailTemplateDao;
	
	@Override
	public List<EmailTemplate> getAllEmailTemplate() {
		EmailTemplateFilter filter = new EmailTemplateFilter();
		return emailTemplateDao.getAllEmailTemplate(filter);
	}

	public IEmailTemplateDao getEmailTemplateDao() {
		return emailTemplateDao;
	}

	public void setEmailTemplateDao(IEmailTemplateDao emailTemplateDao) {
		this.emailTemplateDao = emailTemplateDao;
	}

	@Override
	@Transactional(readOnly = false)
	public void addTemplate(EmailTemplate emailTemplate) {
		if(emailTemplate.getIsDefault()) {
			emailTemplateDao.updateDefault(emailTemplate.getEmailToSendType().getId());
		}
		emailTemplateDao.add(emailTemplate);
	}
	
	@Override
	public List<EmailTemplate> getAllEmailTemplatePaginatedByFilter(
			EmailTemplateFilter emailTypeToSend, int startRecord) {
		return emailTemplateDao.getAllEmailTemplatePaginatedByFilter(emailTypeToSend, startRecord);
	}

	@Override
	public int getAllEmailTemplatePaginatedCountByFilter(EmailTemplateFilter emailTypeToSend) {
		return emailTemplateDao.getAllEmailTemplatePaginatedCountByFilter(emailTypeToSend);
	}

	@Transactional(readOnly = false)
	public void deleteEmailTemplate(EmailTemplate selectedEmailTemplate) {
		selectedEmailTemplate.setActive(Boolean.FALSE);
		emailTemplateDao.update(selectedEmailTemplate);
	}
	
	@Override
	@Transactional(readOnly = false)
	public void updateTemplate(EmailTemplate emailTemplate) {
		if(emailTemplate.getIsDefault()) {
			emailTemplateDao.updateDefault(emailTemplate.getEmailToSendType().getId());
		}
		emailTemplateDao.update(emailTemplate);
	}

	@Override
	public EmailTemplate getEmailTemplateByFilter(
			EmailTemplateFilter emailTemplateFilter) {
		return emailTemplateDao.getEmailTemplateByFilter(emailTemplateFilter);
	}
}
